// controllers/order.go
package controllers

import (
	"myapi/models"
	"myapi/repositories"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// OrderController 处理订单相关请求
type OrderController struct {
	orderRepo repositories.OrderRepository
	userRepo  repositories.UserRepository
}

// NewOrderController 创建订单控制器实例
func NewOrderController() *OrderController {
	return &OrderController{
		orderRepo: repositories.OrderRepository{},
		userRepo:  repositories.UserRepository{},
	}
}

// CreateOrder 创建订单
func (c *OrderController) CreateOrder(ctx *gin.Context) {
	var req models.CreateOrderRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误: " + err.Error()})
		return
	}

	// 验证客户是否存在
	_, err := c.userRepo.FindByID(req.CustomerID)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "客户不存在: " + err.Error()})
		return
	}

	// 验证创建人是否存在
	_, err = c.userRepo.FindByID(req.CreatorID)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "创建人不存在: " + err.Error()})
		return
	}

	// 创建订单
	order := &models.Order{
		CustomerID: req.CustomerID,
		CreatorID:  req.CreatorID,
		Remark:     req.Remark,
		OrderDate:  req.OrderDate,
		Status:     models.OrderStatusPending,
	}

	// 创建订单项
	for _, itemReq := range req.Items {
		item := models.OrderItem{
			ProductName: itemReq.ProductName,
			ProductSpec: itemReq.ProductSpec,
			Quantity:    itemReq.Quantity,
			UnitPrice:   itemReq.UnitPrice,
		}
		order.Items = append(order.Items, item)
	}

	// 保存订单
	if err := c.orderRepo.Create(order); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "创建订单失败: " + err.Error()})
		return
	}

	// 重新查询订单以获取完整信息
	createdOrder, err := c.orderRepo.FindByID(order.ID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "查询订单失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusCreated, gin.H{
		"message": "订单创建成功",
		"data":    createdOrder.ToResponse(),
	})
}

// GetOrder 获取单个订单
func (c *OrderController) GetOrder(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效的订单ID"})
		return
	}

	order, err := c.orderRepo.FindByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data": order.ToResponse(),
	})
}

// GetOrders 获取订单列表
func (c *OrderController) GetOrders(ctx *gin.Context) {
	// 获取分页参数
	pageStr := ctx.DefaultQuery("page", "1")
	pageSizeStr := ctx.DefaultQuery("page_size", "10")

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil || pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	// 获取筛选参数
	customerIDStr := ctx.Query("customer_id")
	status := ctx.Query("status")

	var orders []models.Order
	var count int64

	if customerIDStr != "" {
		// 按客户ID筛选
		customerID, err := strconv.ParseUint(customerIDStr, 10, 32)
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效的客户ID"})
			return
		}
		orders, count, err = c.orderRepo.FindByCustomerID(uint(customerID), page, pageSize)
	} else if status != "" {
		// 按状态筛选
		orders, count, err = c.orderRepo.FindByStatus(models.OrderStatus(status), page, pageSize)
	} else {
		// 获取所有订单
		orders, count, err = c.orderRepo.FindAll(page, pageSize)
	}

	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "查询订单失败: " + err.Error()})
		return
	}

	// 转换为响应格式
	responses := make([]models.OrderResponse, len(orders))
	for i, order := range orders {
		responses[i] = order.ToResponse()
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data": responses,
		"pagination": gin.H{
			"page":       page,
			"page_size":  pageSize,
			"total":      count,
			"total_page": (count + int64(pageSize) - 1) / int64(pageSize),
		},
	})
}

// UpdateOrderStatus 更新订单状态
func (c *OrderController) UpdateOrderStatus(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效的订单ID"})
		return
	}

	var req struct {
		Status models.OrderStatus `json:"status" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误: " + err.Error()})
		return
	}

	// 验证订单是否存在
	_, err = c.orderRepo.FindByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
		return
	}

	// 更新状态
	if err := c.orderRepo.UpdateStatus(uint(id), req.Status); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "更新订单状态失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"message": "订单状态更新成功",
	})
}

// DeleteOrder 删除订单
func (c *OrderController) DeleteOrder(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效的订单ID"})
		return
	}

	// 验证订单是否存在
	_, err = c.orderRepo.FindByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
		return
	}

	// 删除订单
	if err := c.orderRepo.Delete(uint(id)); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "删除订单失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"message": "订单删除成功",
	})
}

// GetOrderStatistics 获取订单统计信息
func (c *OrderController) GetOrderStatistics(ctx *gin.Context) {
	stats, err := c.orderRepo.GetOrderStatistics()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计信息失败: " + err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"data": stats,
	})
}
